/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.rayson.share.http;

import org.rayson.api.struct.HttpResponseStatus;
import org.rayson.share.transport.ByteArrayBuffer;

/**
 * Stands for an HTTP status line of an {@link HttpResponse}.
 * 
 * @author creativor
 */
public class HttpStatusLine implements HttpStartLine {

	private String version;
	private int statusCode;
	private String reasonPhrase;

	private HttpStatusLine() {
	}

	public HttpStatusLine(final HttpResponseStatus status) {
		this(HttpConstants.HTTP_VERSION, status.getCode(), status
				.getReasonPhrase());
	}

	public HttpStatusLine(final int statusCode, final String reasonPhrase) {
		this(HttpConstants.HTTP_VERSION, statusCode, reasonPhrase);
	}

	public HttpStatusLine(final String version, final HttpResponseStatus status) {
		this(version, status.getCode(), status.getReasonPhrase());
	}

	public HttpStatusLine(final String version, final int statusCode,
			final String reasonPhrase) {
		super();
		if (version == null)
			throw new IllegalArgumentException("version should not be null");
		if (reasonPhrase == null)
			throw new IllegalArgumentException(
					"reasonPhrase should not be null");

		this.version = version;
		this.statusCode = statusCode;
		this.reasonPhrase = reasonPhrase;
	}

	@Override
	public HttpStatusLine clone() {
		final HttpStatusLine clone = new HttpStatusLine();
		clone.version = this.version;
		clone.statusCode = this.statusCode;
		clone.reasonPhrase = this.reasonPhrase;
		return clone;
	}

	@Override
	public String toString() {
		final StringBuffer sb = new StringBuffer();
		final Object[] values = { version, statusCode, reasonPhrase };
		final String[] keys = { "version", "statusCode", "reasonPhrase" };
		final int keyLen = keys.length;
		sb.append("{");
		for (int i = 0; i < keyLen; i++) {
			sb.append(keys[i]);
			sb.append(":");
			sb.append(values[i]);
			if (i != keyLen - 1)
				sb.append(", ");
		}
		sb.append("}");
		return sb.toString();
	}

	@Override
	public void writeTo(final ByteArrayBuffer buffer) {
		buffer.write(version.getBytes());
		buffer.write(HttpConstants.SPACE);
		buffer.write(String.valueOf(statusCode).getBytes());
		buffer.write(HttpConstants.SPACE);
		buffer.write(reasonPhrase.getBytes());
		buffer.write(HttpConstants.CRLF);
	}
}